package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.RealLandBase;
import com.atguigu.eduservice.entity.excel.LandExcel;
import com.atguigu.eduservice.mapper.RealLandBaseMapper;
import com.atguigu.eduservice.service.RealLandBaseService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
public class LandExcelListener extends AnalysisEventListener<LandExcel> {
    @Resource
    public RealLandBaseService realLandBaseService;

    public RealLandBaseMapper realLandBaseMapper;


    /**
     * 每隔10条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 20;
    List<RealLandBase> list = new ArrayList();

    public LandExcelListener() {

    }

    public LandExcelListener(RealLandBaseService realLandBaseService,RealLandBaseMapper realLandBaseMapper) {
        this.realLandBaseService = realLandBaseService;
        this.realLandBaseMapper = realLandBaseMapper;
    }

    @Override
    public void invoke(LandExcel data, AnalysisContext context) {

        System.out.println("行"+context.readRowHolder().getRowIndex());
        Integer sheetNo = context.readSheetHolder().getSheetNo();
        if (data ==null) {
            throw new GuliException(20001,"文件数据为空");
        }

        if(sheetNo== 1){
            RealLandBase realLandBase = new RealLandBase();
            BeanUtils.copyProperties(data,realLandBase);
                //生成uuid
            String uuid = UUID.randomUUID().toString();
            realLandBase.setRealLandId(uuid);
                //规划用途
            realLandBase.setPlanPurposeCode(realLandBaseMapper.getItemCode(data.getPlanPurposeName()));
                //土地性质
            realLandBase.setLandCharacterCode(realLandBaseMapper.getItemCode(data.getLandCharacterName()));
                //土地使用权类型
            realLandBase.setLandUseTypeCode(realLandBaseMapper.getItemCode(data.getLandUseTypeName()));
                //是否有证hasCertificateFlag
            if ("是".equals(data.getHasCertificateFlagString())) {
                realLandBase.setHasCertificateFlag(1);
            }
            if ("否".equals(data.getHasCertificateFlagString())) {
                realLandBase.setHasCertificateFlag(0);
            }
                //无证原因
            realLandBase.setNoLicenseReasonCode(realLandBaseMapper.getItemCode(data.getNoLicenseReasonName()));
                //省
            realLandBase.setAreaProvinceCode(realLandBaseMapper.getItemCode(data.getAreaProvinceName()));
                //市
            realLandBase.setAreaCityCode(realLandBaseMapper.getItemCode(data.getAreaCityName()));
                //县
            realLandBase.setAreaCountyCode(realLandBaseMapper.getItemCode(data.getAreaCountyName()));

            realLandBase.setProvinceCompanyId(realLandBaseMapper.organizationName(data.getProvinceCompanyName()));

            realLandBase.setCityCompanyId(realLandBaseMapper.organizationName(data.getCityCompanyName()));

            realLandBase.setCountyCompanyId(realLandBaseMapper.organizationName(data.getCountyCompanyName()));

                // 设置状态，默认为1
            realLandBase.setStatusFlag(1);
                //可见业务类型
            realLandBase.setTypeOfService("1");

            realLandBase.setCreateTime(new Date());

            //闲置面积 =  土地面积-使用面积
            BigDecimal subtract = data.getUsefulArea().subtract(data.getUsedArea());
            realLandBase.setIdleArea(subtract);

            //==========================================
            realLandBase.setActualLandUseCode(data.getActualLandUseName());
            realLandBase.setLandGradesCode(data.getLandGradesName());
            realLandBase.setAssetsIncreaseWayCode(data.getAssetsIncreaseWayName());
            realLandBase.setPhysicalManagementDepartmentId(data.getPhysicalManagementDepartmentName());
            realLandBase.setUseProvinceCompanyId(data.getUseProvinceCompanyName());
            realLandBase.setUseCityCompanyId(data.getUseCityCompanyName());
            realLandBase.setUseCountyCompanyId(data.getUseCountyCompanyName());
            realLandBase.setUseDepartmentId(data.getUseDepartmentName());


            log.info("解析到一条记录: {}", realLandBase);
            list.add(realLandBase);
                //达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
            if (list.size() >= BATCH_COUNT) {
                saveData();
                    // 存储完成清理 list
                list.clear();
            }

        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
//         这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
        System.out.println("list" + list);
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        realLandBaseService.insertBatch(list);  //批量插入
        log.info("存储数据库成功！");
    }
}
